//
//  GPSRecordListController.m
//  Portable Traffic Signal Assistor
//
//  Created by Ding on 10/15/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "GPSRecordListController.h"
#define CONST_Cell_height 40
#define CONST_Cell_width 40

@interface GPSRecordListController ()

@end

@implementation GPSRecordListController
@synthesize GPSRecordNameSection=_GPSRecordNameSection;
@synthesize sections=_sections;
@synthesize signal=_signal;
@synthesize agency=_agency;
@synthesize subSystem=_subSystem;
@synthesize timingPattern=_timingPattern;
@synthesize textViewArray=_textViewArray;


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil agency:(Agency *)agency subsystem:(SubSystem *)subsystem timingPattern:(TimingPattern *)timingPattern signal:(Signal *)signal
{
    self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.signal=signal;
        self.agency=agency;
        self.subSystem=subsystem;
        self.timingPattern=timingPattern;
    }
    return self;
}

-(void) dealloc
{
    [_sections release];
    [_GPSRecordNameSection release];
    [_signal release];
    [_agency release];
    [_subSystem release];
    [_timingPattern release];
    [_textViewArray release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    [self.tableView.st]

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    if (!_textViewArray) {
        _textViewArray=[[NSMutableArray alloc] init];
    }
    if(!_GPSRecordNameSection)
    {
        _GPSRecordNameSection=[[TableSection alloc]init];
        
        _GPSRecordNameSection.contents=[[[NSMutableArray alloc] initWithArray:[self getGPSRecordNameList]] autorelease];

        _GPSRecordNameSection.header=@"GPS Record List";
    }
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
        [_sections addObject:_GPSRecordNameSection];
    }
    UITapGestureRecognizer *gestureRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewReturn:)] autorelease];
    gestureRecognizer.enabled = YES;
    gestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:gestureRecognizer];
}

-(void) viewDidUnload
{
    self.sections=nil;
    self.GPSRecordNameSection=nil;
    self.textViewArray=nil;
    [super viewDidUnload];
}
-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    _GPSRecordNameSection.contents=[[[NSMutableArray alloc] initWithArray:[self getGPSRecordNameList]] autorelease];
//    [self.tableView reloadData];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=UILineBreakModeWordWrap;
    cell.textLabel.text=sectionContentString;
    
    UITextView *recordTextView=[[[UITextView alloc] initWithFrame:CGRectMake(5,1 , cell.frame.size.width-60, cell.frame.size.height-2)] autorelease];
    //[recordTextField setPlaceholder:@"Building Name"];
    //                    [self.facilityNewBuildingNameText setText:sectionContentString];
    [recordTextView setFont:[UIFont fontWithName:@"ArialMT" size:14]];
    [recordTextView setTag:indexPath.row];
    //[facilityNewBuildingNameText set
    //[facilityNewBuildingNameText];
    recordTextView.delegate=self;
    //                    cell.detailTextLabel.text=@"Building Name";
    recordTextView.text=sectionContentString;
    [recordTextView setReturnKeyType: UIReturnKeyDone];
    [[cell contentView] addSubview:recordTextView];
    [self.textViewArray addObject:recordTextView];
//    [cell setBackgroundColor:[TableSection WhiteColor]];
    /*
    UITextField *recordTextField=[[[UITextField alloc] initWithFrame:CGRectMake(1, 5, cell.frame.size.width-2, cell.frame.size.height-10)] autorelease];
    //[recordTextField setPlaceholder:@"Building Name"];
    //                    [self.facilityNewBuildingNameText setText:sectionContentString];
    [recordTextField setFont:[TableSection TitleFont]];
    [recordTextField setTag:indexPath.row];
    //[facilityNewBuildingNameText set
    //[facilityNewBuildingNameText];
    recordTextField.delegate=self;
    //                    cell.detailTextLabel.text=@"Building Name";
    recordTextField.text=sectionContentString;
    [[cell contentView] addSubview:recordTextField];
    [cell setBackgroundColor:[TableSection WhiteColor]];
     */
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // Commit the delete
        [self removeGPSRecord:indexPath];
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    UIActivityIndicatorView * activityIndicator = [[[UIActivityIndicatorView alloc] initWithFrame: CGRectMake(100,150,120,120)] autorelease];
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryView = activityIndicator;
//    [self.view addSubview:activityIndicator];
//    [self.vi bring]
    [activityIndicator startAnimating];
    
    [NSThread detachNewThreadSelector:@selector(loadHistoricalTSDView:) toTarget:self withObject:indexPath];
}
-(void) loadHistoricalTSDView:(id) obj {
    TimeSpaceHistoryViewController *timeSpaceViewController=[[[TimeSpaceHistoryViewController alloc] initWithNibName:@"TimeSpaceViewController" bundle:nil agency:self.agency subsystem:self.subSystem timingPattern:self.timingPattern signal:self.signal direction:NORTHBOUND GPSRecordName:[self.GPSRecordNameSection.contents objectAtIndex:[(NSIndexPath *)obj row]]] autorelease];
    [timeSpaceViewController setTitle:@"Historical Time Space View"];
    UINavigationController * parentController=self.navigationController;
    [parentController pushViewController:timeSpaceViewController animated:YES];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:(NSIndexPath *)obj];
//    UIButton *accessoryButton=[[UIButton buttonWithType:UIButtonTypeDetailDisclosure] autorelease];
    cell.accessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
//    TimeSpaceHistoryViewController *timeSpaceHistoryController=[[TimeSpaceHistoryViewController alloc] initWithNibName:@"TimeSpaceHistoryViewController" bundle:nil agency:self.agency subsystem:self.subSystem timingPattern:self.timingPattern signal:self.signal direction:NORTHBOUND GPSRecordName:[self.GPSRecordNameSection.contents objectAtIndex:indexPath.row]];
//    
//    [timeSpaceHistoryController setTitle:@"History View Controller"];
//    [self.navigationController pushViewController:timeSpaceHistoryController animated:YES];
    
   /* TimeSpaceHistoryViewController *timeSpaceViewController=[[[TimeSpaceHistoryViewController alloc] initWithNibName:@"TimeSpaceViewController" bundle:nil agency:self.agency subsystem:self.subSystem timingPattern:self.timingPattern signal:self.signal direction:NORTHBOUND GPSRecordName:[self.GPSRecordNameSection.contents objectAtIndex:indexPath.row]] autorelease];
    [timeSpaceViewController setTitle:@"Historical Time Space View"];
    UINavigationController * parentController=self.navigationController;
    [parentController pushViewController:timeSpaceViewController animated:YES];*/
}
#pragma mark -TextView Delegate
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
//    self.agency.agencyName=textView.text;
//    [XMLParser updateAgency:self.agency];
//    self.agencyNameSection=[[[TableSection alloc]init] autorelease];
//    
//    //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
//    self.agencyNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
//    [self.agencyNameSection.contents addObject:self.agency.agencyName];
//    
//    self.agencyNameSection.header=@"Agency Name";
    // For error information
    NSError *error;
    
    // Create file manager
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    
    if (textView.tag<0||textView.tag>=self.GPSRecordNameSection.contents.count) {
        return YES;
    }
    NSString * logFilePath = [[[NSString alloc] initWithFormat:@"%@/%@.gps",documentsDir,[self.GPSRecordNameSection.contents objectAtIndex:textView.tag]] autorelease];
    NSString * logFilePath2 = [[[NSString alloc] initWithFormat:@"%@/%@.gps",documentsDir,textView.text] autorelease];
    // Attempt the move
    if ([fileMgr moveItemAtPath:logFilePath toPath:logFilePath2 error:&error] != YES)
    {
        NSLog(@"Unable to move file: %@", [error localizedDescription]);
    }
        
    
    // Show contents of Documents directory
    NSLog(@"Documents directory: %@",
          [fileMgr contentsOfDirectoryAtPath:documentsDir error:&error]);
    [self.GPSRecordNameSection.contents replaceObjectAtIndex:textView.tag withObject:textView.text];
    [self.textViewArray removeAllObjects];
    [self.tableView reloadData];
    return YES;
}

- (NSArray *)getGPSRecordNameList
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSMutableArray *GPSRecordNameList=[[[NSMutableArray alloc] init] autorelease];
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    
    //sort files by createdate
        NSError* error = nil;
        NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];
        if(error != nil) {
            NSLog(@"Error in reading files: %@", [error localizedDescription]);
            return nil;
        }
        
        // sort by creation date
        NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]];
        for(NSString* file in filesArray) {
            NSString* filePath = [documentsDirectory stringByAppendingPathComponent:file];
            NSDictionary* properties = [[NSFileManager defaultManager]
                                        attributesOfItemAtPath:filePath
                                        error:&error];
            NSDate* createDate = [properties objectForKey:NSFileCreationDate];
            
            if(error == nil)
            {
                [filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                               file, @"path",
                                               createDate, @"createDate",
                                               nil]];
            }
        }
        
        // sort using a block
        // order inverted as we want latest date first
        NSArray* sortedFiles = [filesAndProperties sortedArrayUsingComparator:
                                ^(id path1, id path2)
                                {
                                    // compare
                                    NSComparisonResult comp = [[path1 objectForKey:@"createDate"] compare:
                                                               [path2 objectForKey:@"createDate"]];
                                    // invert ordering
                                    if (comp == NSOrderedDescending) {
                                        comp = NSOrderedAscending;
                                    }
                                    else if(comp == NSOrderedAscending){
                                        comp = NSOrderedDescending;
                                    }
                                    return comp;                                
                                }];
    
    
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (int i=0; i<sortedFiles.count; i++) {
        NSDictionary *dic=[sortedFiles objectAtIndex:i];
        [tempArray addObject:[dic objectForKey:@"path"]];
    }
    NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.gps'"];
    NSArray *array = [tempArray filteredArrayUsingPredicate:fltr];
    
    for (int i=0; i<[array count]; i++) {
        NSRange projectIDRange=[[array objectAtIndex:i] rangeOfString:@"."];
        
        NSString *projectID=[[array objectAtIndex:i] substringToIndex:projectIDRange.location];
        [GPSRecordNameList addObject:projectID];
    }
    return GPSRecordNameList;

}

- (void)removeGPSRecord:(NSIndexPath *)indexPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentPath = [documentsDirectory stringByAppendingPathComponent:[[self.GPSRecordNameSection.contents objectAtIndex:indexPath.row] stringByAppendingPathExtension:@"gps"]];
    NSLog(@"%@", documentPath);
    NSError *error=[[[NSError alloc] init]autorelease];
    if (![[NSFileManager defaultManager] removeItemAtPath:documentPath error:&error])	//Delete it
    {
        NSLog(@"Delete file error: %@", error);
        
    }
    _GPSRecordNameSection.contents=[[[NSMutableArray alloc] initWithArray:[self getGPSRecordNameList]] autorelease];
    [self.tableView reloadData];

}

- (IBAction)textViewReturn:(id)sender
{
    for (UITextView *textView in self.textViewArray) {
        if ([textView isFirstResponder]) {
            [textView resignFirstResponder];
            return;
        }
    
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}


@end
